package com.health.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.mapper.UserMapper;
import com.health.pojo.User;
import com.health.service.UserService;
import com.health.utils.JwtUtil;
import com.health.vo.UserLoginVO;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @Override
    public UserLoginVO login(User user) {
        //1. 根据用户名密码查询
        User dbUser = this.query().eq("username", user.getUsername()).one();
        if (dbUser == null) {
            //说明用户名不存在
            throw new RuntimeException("用户名不存在");
        }

        //2. 比较dbUser 和 user 之间的密码
        if (!dbUser.getPassword().equals(user.getPassword())) {
            //说明密码错误
            throw new RuntimeException("密码错误");
        }

        //3. 判断用户的状态是否正常
        if (dbUser.getStatus() == 0) {
            throw new RuntimeException("用户被禁用");
        }

        //4. 说明用户登录成功，生成jwt令牌
        Map<String, Object> map = Map.of("id", dbUser.getId());
        String jwt = JwtUtil.createJwt(map);

        //5. 封装返回数据
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(dbUser.getId());
        userLoginVO.setUsername(dbUser.getUsername());
        userLoginVO.setToken(jwt);

        return userLoginVO;
    }
}
